package com.example.sms.controller;

import com.example.sms.service.SendSms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class SmsController
{
    @Autowired
    SendSms sendSms;

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @GetMapping("/send/{phone}")
    public String send(@PathVariable("phone") String phone){
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return "已存在，还未过期！";
        }
        code = UUID.randomUUID().toString().substring(0, 4);
        HashMap<String, Object> map = new HashMap<>();
        map.put("code",code);
        boolean isSuccess = sendSms.send(phone, "SMS_189621151", map);
        if(isSuccess){
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return phone+":"+code+" "+"发送成功";
        }
        else {
            return "发送失败！";
        }
    }
}
